package com.itheima.health.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.entity.SecurityUser;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/mobile/login")
public class LoginController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map, HttpSession session) {
        String phoneNumber = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        String codeFromRedis = (String) redisTemplate.opsForValue().get("member_loginPhone:" + phoneNumber);

        if (codeFromRedis == null) {
            return new Result(false, "验证码过期或未点击发送验证码");
        }
        if (!validateCode.equals(codeFromRedis)) {
            return new Result(false, "验证码错误");
        }
        //判断是否新会员
        Member member=memberService.getone(phoneNumber);
        if(member==null){
            member=new Member();
            member.setPhoneNumber(phoneNumber);
            member.setRegTime(new Date());
            memberService.save(member);
        }
        //存入session
         session.setAttribute("member_user",new SecurityUser(member.getId(),member.getName(),
                 member.getPhoneNumber(),member.getPassword()));
        return new Result(true,"登陆成功",member);
    }
}

